var invalidClass = "input-validation-error";
var ajaxCollection = [];
var bluelotus7 = {};
//// ------------------------------------------------------------------
Date.prototype.format = function (mask) {
    var d = this;
    var zeroize = function (value, length) {
        if (!length) length = 2;
        value = String(value);
        for (var i = 0, zeros = ''; i < (length - value.length) ; i++) {
            zeros += '0';
        }
        return zeros + value;
    };

    return mask.replace(/"[^"]*"|'[^']*'|\b(?:d{1,4}|M{1,4}|m{1,2}|yy(?:yy)?|([hHMstT])\1?|[lLZ])\b/g, function ($0) {
        switch ($0) {
            case 'd': return d.getDate();
            case 'dd': return zeroize(d.getDate());
            case 'ddd': return ['Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat'][d.getDay()];
            case 'dddd': return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][d.getDay()];
            case 'M': return d.getMonth() + 1;
            case 'MM': return zeroize(d.getMonth() + 1);
            case 'MMM': return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()];
            case 'MMMM': return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][d.getMonth()];
            case 'yy': return String(d.getFullYear()).substr(2);
            case 'yyyy': return d.getFullYear();
            case 'h': return d.getHours() % 12 || 12;
            case 'hh': return zeroize(d.getHours() % 12 || 12);
            case 'H': return d.getHours();
            case 'HH': return zeroize(d.getHours());
            case 'm': return d.getMinutes();
            case 'mm': return zeroize(d.getMinutes());
            case 's': return d.getSeconds();
            case 'ss': return zeroize(d.getSeconds());
            case 'l': return zeroize(d.getMilliseconds(), 3);
            case 'L': var m = d.getMilliseconds();
                if (m > 99) m = Math.round(m / 10);
                return zeroize(m);
            case 'tt': return d.getHours() < 12 ? 'am' : 'pm';
            case 'TT': return d.getHours() < 12 ? 'AM' : 'PM';
            case 'Z': return d.toUTCString().match(/[A-Z]+$/);
                // Return quoted strings with the surrounding quotes removed
            default: return $0.substr(1, $0.length - 2);
        }
    });
};

function getDateValue(dateTextbox) {
    var date = new Date($(dateTextbox).datepicker("getDate"));
    return date.format("MM/dd/yyyy");
}
//// ------------------------------------------------------------------
function fillText(textContainer, textValue) {
    textContainer.text(textValue);
    textContainer.html(textContainer.text().replace(/\n/gi, '<br />'));
}

function getPlainText(textContainer) {
    return textContainer.html().replace(/\<br \/\>/gi, '\n').replace(/\<br\>/gi, '\n');;
}
//// ------------------------------------------------------------------
var getRandom = function (max, min) {
    if (max) {
        if (!min) {
            min = 0;
        }
        return parseInt(Math.random() * (max - min + 1) + min);
    }
    else {
        return Math.random();
    }
}

function appendRandom(url) {
    if (url) {
        if (url.indexOf("?") > 0) {
            url += "&";
        } else {
            url += "?";
        }
        url += "rand=" + window.getRandom(1000000);
    }

    return url;
}
//// ------------------------------------------------------------------
var errorUtility = {
    init: function (domObject) {
        if (domObject) {
            domObject.addClass("error-container").addClass("validation-summary-errors");
            domObject.children().remove();
            domObject.append("<ul></ul>");
            this.instance = domObject.children();
            return this;
        }
    },
    append: function (msg, code, distinct) {
        if (!distinct || !this.instance.find("li[code='" + code + "']").length) {
            var item = $("<li></li>");
            if (code) {
                item.attr("code", code);
            }

            if (msg) {
                item.text(msg);
                this.instance.append(item);
            }
        }
    },
    remove: function (code) {
        if (code) {
            this.instance.find("li[code='" + code + "']").remove();
        }
    },
    clear: function () {
        this.instance.children().remove();
    },
    errorCount: function () {
        return this.instance.children().length;
    },
    hasError: function () {
        return this.instance.children().length > 0;
    }
};

//// --- Add clear button for jQuery datepicker ---
//$.datepicker._generateHTML_Old = $.datepicker._generateHTML;
//$.datepicker._generateHTML = function (inst) {
//    res = this._generateHTML_Old(inst);
//    res = res.replace("_hideDatepicker()", "_clearDate('#" + inst.id + "')");
//    return res;
//}
//// --- End ---
//// ------------------------------------------------------------------
function DenyInputChar(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (!((charCode >= 48 && charCode <= 57) || charCode == 45 /*-*/ || charCode == 46 /*.*/ || charCode == 8 /*remove key*/)) {
        return false;
    }

    if (charCode == 46 && $(this).val().indexOf(String.fromCharCode(charCode)) > -1) {
        return false;
    }

    if (charCode == 45 && $(this).val().length > 0) {
        return false;
    }


    return true;
}
//// ------------------------------------------------------------------
function isInCollection(collection, value) {
    var result = false;
    if (collection) {
        for (var i = 0; i < collection.length; i++) {
            if (typeof (value) == 'string') {
                if (collection[i].toString().toLowerCase() == value.toLowerCase()) {
                    result = true;
                    break;
                }
            } else {
                if (collection[i] == value) {
                    result = true;
                    break;
                }
            }
        }
    }
    return result;
}

//// ------------------------------------------------------------------
// dateSource
var dataSource = {
    tryInit: function () {
        if (!this.sources) {
            this.sources = [];
        }
    },
    updateSources: function (key, data) {
        if (key && data) {
            this.sources[key] = data;
        }
    },
    getSource: function (key) {
        if (key) {
            return this.sources[key];
        }
    },
    getSourceItemNameByValue: function (key, value) {
        var source = this.getSource(key);
        if (source && value != undefined && value != null) {
            for (var i = 0; i < source.length; i++) {
                if (source[i].Key == value) {
                    return source[i].Value;
                }
            }
        }
    },
    getBooleanSource: function (key, textMapping, valueMapping) {
        var result = $("<div></div>");
        var data = this.getSource(key);
        result.attr("source", key);
        this.fillBooleanSource(result, data, textMapping, valueMapping);
        return result;
    },
    fillBooleanSource: function (container, data, textMapping, valueMapping) {
        if (!container || !container.length) {
            container = $("<div></div>");
        }
        if (data && data.length) {
            container.addClass('boolean');
            textMapping = textMapping ? textMapping : "Value";
            valueMapping = valueMapping ? valueMapping : "Key";
            for (var i = 0; i < data.length; i++) {
                var t = data[i][textMapping];
                var v = data[i][valueMapping];
                v = v != undefined && v != null ? v : t;
                var label = $("<label></label>");
                label.text(t);
                var option = $("<input type='checkbox' />");
                option.attr("value", v);
                label.prepend(option);
                container.append(label);
            }
        }
        return container;
    },
    getComboSource: function (key, textMapping, valueMapping, selectedValue) {
        var result = $("<select></select>");
        var data = this.getSource(key);
        result.attr("source", key);
        this.fillComboSource(result, data, textMapping, valueMapping, selectedValue);
        return result;
    },
    fillComboSource: function (container, data, textMapping, valueMapping, selectedValue) {
        if (!container || !container.length) {
            container = $("<select></select>");
        }
        if (data && data.length) {
            container.addClass('combo');
            textMapping = textMapping ? textMapping : "Value";
            valueMapping = valueMapping ? valueMapping : "Key";
            for (var i = 0; i < data.length; i++) {
                var t = data[i][textMapping];
                var v = data[i][valueMapping];
                v = v != undefined && v != null ? v : t;
                var option = $("<option></option>");
                option.attr("value", v);
                option.text(t);
                if (v == selectedValue) {
                    option.attr("selected", true);
                }
                container.append(option);
            }
        }
        return container;
    },
    getRadioSource: function (key, textMapping, valueMapping, selectedValue, css) {
        var result = $("<div></div>");
        var data = this.getSource(key);
        result.attr("source", key);
        this.fillRadioSource(result, data, textMapping, valueMapping, selectedValue);
        return result;
    },
    fillRadioSource: function (container, data, textMapping, valueMapping, selectedValue) {
        if (!container || !container.length) {
            container = $("<div></div>");
        }
        if (data && data.length) {
            container.addClass('radio');
            textMapping = textMapping ? textMapping : "Value";
            valueMapping = valueMapping ? valueMapping : "Key";
            var radioName = this.getRandomName();
            var hasChecked = false;
            for (var i = 0; i < data.length; i++) {
                var t = data[i][textMapping];
                var v = data[i][valueMapping];
                v = v != undefined && v != null ? v : t;
                var option = $("<label></label>");
                var radiobox = $("<input type='radio' />")
                radiobox.attr("value", v);
                radiobox.attr("name", radioName);
                if (v == selectedValue) {
                    radiobox.attr("checked", true);
                    hasChecked = true;
                }
                option.append(radiobox).append(t);
                container.append(option);
            }

            if (!hasChecked) {
                container.children(":first").find("input:radio").attr("checked", true);
            }
        }
        return container;
    },
    getRandomName: function () {
        var currentTime = new Date();
        var rnd = getRandom(1000000);
        return "ctl" + currentTime.getTime() + rnd;
    },
    addSourceRange: function (arrayObject) {
        if (arrayObject && arrayObject.length) {
            for (var i = 0; i < arrayObject.length; i++) {
                this.updateSources(arrayObject[i].Key, arrayObject[i].Items);
            }
        }
    }
}

window.dataSources = dataSource.tryInit();
//// ------------------------------------------------------------------
(function () {
    $.extend($.fn, {
        mask: function (msg, maskDivClass) {
            this.unmask();
            var op = {
                opacity: 0.8,
                z: 10000,
                bgcolor: '#ccc'
            };
            var original = $(document.body);
            var position = { top: 0, left: 0 };
            if (this[0] && this[0] !== window.document) {
                original = this;
                position = original.position();
            }
            var maskDiv = $('<div class="maskdivgen"> </div>');
            maskDiv.appendTo(original);
            var maskWidth = original.outerWidth();
            if (!maskWidth) {
                maskWidth = original.width();
            }
            var maskHeight = original.outerHeight();
            if (!maskHeight) {
                maskHeight = original.height();
            }
            maskDiv.css({
                position: 'absolute',
                top: position.top,
                left: position.left,
                'z-index': op.z,
                width: maskWidth,
                height: maskHeight,
                'background-color': op.bgcolor,
                opacity: 0
            });

            if (maskDivClass) {
                maskDiv.addClass(maskDivClass);
            }
            if (msg) {
                var msgDiv = $('<div style="position:absolute;border:#6593cf 1px solid; padding:2px;background:#ccca"><div style="line-height:24px;border:#a3bad9 1px solid;background:white;padding:2px 10px 2px 10px">' + msg + '</div></div>');
                msgDiv.appendTo(maskDiv);
                var widthspace = (maskDiv.width() - msgDiv.width());
                var heightspace = (maskDiv.height() - msgDiv.height());
                msgDiv.css({
                    cursor: 'wait',
                    top: (heightspace / 2 - 2),
                    left: (widthspace / 2 - 2)
                });
            }
            maskDiv.fadeIn('fast', function () {
                $(this).fadeTo('slow', op.opacity);
            });
            return maskDiv;
        },
        unmask: function () {
            var original = $(document.body);
            if (this[0] && this[0] !== window.document) {
                original = $(this[0]);
            }
            original.find("> div.maskdivgen").fadeOut('slow', 0, function () {
                $(this).remove();
            });
        }
    });
})();
//// ------------------------------------------------------------------
bluelotus7.mask = function (container, text) {
    if (!container) {
        container = $("window");
    }
    if (!text) {
        text = "Please wait...";
    }
    container.mask(text);
    return container;
}
bluelotus7.unmask = function (container) {
    if (!container) {
        container = $("window");
    }
    container.unmask();
}
//// ------------------------------------------------------------------
bluelotus7.initDatepicker = function (container) {
    if (!container) {
        container = $("body");
    }

    container.find("input[type='date']").attr("readonly", true).bind("keyup", {}, function (e) {
        if (e.keyCode == 8 || e.keyCode == 46) {
            $(this).val("");
        }
        return false;
    }).datepicker({
        dateFormat: "yy-mm-dd",
        changeMonth: true,
        changeYear: true
    });
}
//// ------------------------------------------------------------------
var formUtil = {
    constActionPanel: "actionPanel",
    setToReadonly: function (container) {
        if (container) {
            var fields = container.find("div.field");
            fields.find("span.readonly").show();
            fields.find("span.edit").hide();
        }
    },
    setToEdit: function (container) {
        if (container) {
            var fields = container.find("div.field:has(span.edit)");
            fields.find("span.readonly").hide();
            fields.find("span.edit").show();
        }
    },
    switchButton: function (container, toReadonly) {
        if (container) {
            if (!container.hasClass(this.constActionPanel)) {
                container = container.find("." + this.constActionPanel);
            }

            if (toReadonly) {
                container.find(".btn-edit, .btn-ok").show();
                container.find(".btn-cancel, .btn-submit").hide();
            }
            else {
                container.find(".btn-edit, .btn-ok").hide();
                container.find(".btn-cancel, .btn-submit").show();
            }
        }
    },
    getData: function (container, originalData) {
        return this.handleData(container, 'get', originalData);
    },
    setData: function (container, data) {
        this.handleData(container, 'set', data);
    },
    applyNewData: function (container) {
        this.handleData(container, 'apply');
    },
    cancelData: function (container) {
        this.handleData(container, 'cancel');
    },
    handleData: function (panelObj, mode, originalData) {
        if (!originalData) {
            originalData = panelObj.data("original");
        }
        var fields = panelObj.find("div.field");
        for (var i = 0; i < fields.length; i++) {
            var current = fields.eq(i);
            var fieldKey = current.attr('name');
            if (!fieldKey) {
                break;
            }
            var dataValue = this.getValue(current.children('span.edit'), true);
            switch (mode) {
                case "get":
                    if (dataValue == undefined) {
                        dataValue = { value: $.trim(current.children('span.readonly').text()) };
                    }
                    if (dataValue != undefined) {
                        originalData[fieldKey] = dataValue.value;
                    }
                    break;
                case "set":
                    this.setValue(current.children('span.edit'), originalData[fieldKey]);
                    break;
                case "cancel":
                    var readonlyValue = current.children('span.edit').attr("value") || current.children('span.readonly').text();
                    setValue(current.children('span.edit'), readonlyValue);
                    break;
                case "apply":
                    if (dataValue) {
                        current.children('span.readonly').text($.trim(dataValue.text));
                        current.children('span.edit').attr("value", dataValue.value);
                    }
                    break;
                default:
                    break;
            }
        }
        return originalData;
    },
    getValue: function (spanObj, includeText) {
        if (spanObj && spanObj.length) {
            var value, text;
            var options = spanObj.find("option");
            if (options && options.length) {
                var selectedItem = options.filter(":selected");
                value = selectedItem.attr("value");
                text = $.trim(selectedItem.text());
            } else {
                value = text = $.trim(spanObj.children().val());
            }
            return includeText ? { value: value, text: text } : value;
        }
    },
    setValue: function (spanObj, value) {
        if (spanObj && spanObj.length) {
            var options = spanObj.find("option");
            if (options && options.length) {
                options.filter("option[value='" + value + "']").attr("selected", true);
            } else {
                spanObj.children().val(value);
            }
        }
    }
}
//// ------------------------------------------------------------------
bluelotus7.ajaxCollection = [];